// 2025/10/14: 首个版本
// 2025/11/12: 自动选中选项

using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using ASEva;
using ASEva.Utility;

namespace CommonSource
{
    partial class Debugger : Window
    {
        public Debugger()
        {
            InitializeComponent();
            DataContext = model;

            var chinese = AgencyLocal.GetAppLanguage() == Language.Chinese;
            Title = chinese ? "调试窗口" : "Debugger";

            if (FuncManager.Run("System.GetDesignerModeFlag") == null)
            {
                debuggerPanel.ModuleID = "debugger";
                debuggerPanel.SetTargetID("General");

                debuggerPanel.ExportRequest += async delegate
                {
                    var selected = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
                    {
                        FileTypeChoices = [ new FilePickerFileType(chinese ? "文本文件(*.txt)" : "Text File (*.txt)"){ Patterns = [ "*.txt" ] } ]
                    });
                    if (selected != null) debuggerPanel.ExportMessages(selected.Path.AbsolutePath);
                };
            }

            Closing += (sender, args) =>
            {
                IsVisible = false;
                args.Cancel = true;
            };

            listBox.SelectionChanged += delegate
            {
                debuggerPanel.SetTargetID(model.SelectedItem?.Id);
            };
        }
        
        public DebuggerPanel Panel => debuggerPanel;

        public void UpdateList()
        {
            if (!interval.Test()) return;

            var table = debuggerPanel.GetCountTable();
            foreach (var item in model.Items)
            {
                if (table.ContainsKey(item.Id)) item.Title = item.Id + "(" + table[item.Id] + ")";
                else model.Items.Remove(item);
            }
            foreach (var id in table.Keys)
            {
                if (model.Items.ToList().Exists(item => item.Id == id)) continue;
                int index = 0;
                for (; index < model.Items.Count; index++)
                {
                    if (model.Items[index].Id.CompareTo(id) > 0) break;
                }

                var newItem = new ListItem(id, id + "(" + table[id] + ")");
                model.Items.Insert(index, newItem);
                if (debuggerPanel.TargetID == id) model.SelectedItem = newItem;
            }

            debuggerPanel.QueueRender();
        }

        protected override void IsVisibleChanged(AvaloniaPropertyChangedEventArgs e)
        {
            base.IsVisibleChanged(e);
            if (IsVisible)
            {
                debuggerPanel.InputMessages(new Dictionary<string, List<string>>
                {
                    ["dump.Exception"] = Dump.ClearExceptions().ToList(),
                });
            }
        }

        partial class ListItem(String id, String title) : ObservableObject
        {
            [ObservableProperty]
            private String id = id;

            [ObservableProperty]
            private String title = title;
        }

        partial class Model : ObservableObject
        {
            [ObservableProperty]
            private ObservableCollection<ListItem> items = [];

            [ObservableProperty]
            private ListItem selectedItem = null;

        }

        private Model model = new();
        private IntervalControl interval = new IntervalControl(0.1);
    }
}